/**
 * Created with IntelliJ IDEA.
 * Description:二叉搜索树
 * User: LXW
 * Date: 2022-03-06
 * Time: 11:09
 */
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node(int val) {
        this.val = val;
    }
}
public class BinarySearchTree {
    public Node root = null;
    public static void main(String[] args) {

    }
    public Node search(Node root,int key) {
        if (root == null) {
            return null;
        }
        while(root != null) {
            if (root.val == key) {
                return root;
            }else if (root.val < key) {
                root = root.right;
            }else {
                root = root.left;
            }
        }
        return null;
    }
    public boolean insert(Node root,int val) {
        if (root == null) {
            root = new Node(val);
            return true;
        }
        Node cur = root;
        Node parent = null;
        while (cur.left != null || cur.right != null) {
            if (root.val < val) {
                parent = cur;
                cur = cur.right;
            }else if (root.val > val) {
                parent = cur;
                cur = cur.left;
            }else {
                return false;// 不能插入相同的值
            }
        }
        if (parent.val < val) {
            Node node = new Node(val);
            parent.right = node;
            return true;
        }else {
            Node node = new Node(val);
            parent.left = node;
            return true;
        }
    }
    public void remove(Node root,int key) {
        if (root == null) {
            return;
        }
        Node cur = root;
        Node parent = null;
        while (root != null) {
            if (root.val == key) {
                break;
            }else if (cur.val < key) {
                parent = cur;
                cur = cur.right;
            }else {
                parent = cur;
                cur = cur.left;
            }
        }
        if (cur.left == null) {
            if (cur == root) {
                root = cur.right;
            }else if (cur == parent.left) {
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if (cur.right == null) {
            if (cur == null) {
                root = cur.left;
            }else if (cur == parent.left) {
                parent.right = cur.left;
            }else {
                parent.left = cur.left;
            }
        }else {
            Node targetParent = cur;
            Node target = cur.right;
            while(target.left != null) {
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if (target == targetParent.left) {
                targetParent.left = target.right;
            }else {
                targetParent.right = target.right;
            }
        }
    }
}
